import { network } from "../../utils/network.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    islyric: false,
    isPlayMusic: false,
    id: 0,
    time1: "00:00",
    time2: "00:00",
    checkTimes: [],
    currentIndex222: 0,
    hang: 0,
    playtime: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var id = options.id;

    that.setData({
      id: id,
    })

    if (getApp().globalData.musicid === id) {
      that.setData({
        isPlayMusic: getApp().globalData.isPlayMusic,
        checkTimes: getApp().globalData.checkTimes,
        currentIndex222: getApp().globalData.currentIndex222,
        hang: getApp().globalData.hang,
        playtime: getApp().globalData.stoptime
      })
      let bgMusic = wx.getBackgroundAudioManager();
      bgMusic.onTimeUpdate(() => {
        this.setData({
          time: bgMusic.currentTime,
          alltime: bgMusic.duration,
          time1: this.timeToString(bgMusic.currentTime.toFixed(0)),
          time2: this.timeToString(bgMusic.duration.toFixed(0))
        })
        var i = that.data.currentIndex222
        if (that.data.checkTimes[i] <= bgMusic.currentTime) {
          that.setData({
            currentIndex222: i + 1,
            hang: i
          })
        }
      })
    } else {
      that.setData({
        time1: "00:00",
        time2: "00:00"
      })
    }


    if (options.playnow) {
      this.playnow(id)
      console.log("playnow")
    }
    else {
      this.getData(id)
      console.log("notnow")
    }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this
    // getApp().globalData.isPlayMusic = that.data.isPlayMusic
    getApp().globalData.checkTimes = that.data.checkTimes
    getApp().globalData.currentIndex222 = that.data.currentIndex222
    getApp().globalData.hang = that.data.hang
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    // getApp().globalData.isPlayMusic = that.data.isPlayMusic
    getApp().globalData.checkTimes = that.data.checkTimes
    getApp().globalData.currentIndex222 = that.data.currentIndex222
    getApp().globalData.hang = that.data.hang
  },

  onmusictap: function () {
    var that = this;
    var id = that.data.id;
    console.log("播放时")
    console.log(id)
    if (that.data.isPlayMusic) {
      var stoptime = wx.getBackgroundAudioManager().currentTime
      getApp().globalData.stoptime = stoptime
      wx.pauseBackgroundAudio();
      console.log("stop")
    } else {
      wx.playBackgroundAudio({
        dataUrl: that.data.url,
        title: that.data.song.name,
        coverImgUrl: that.data.song.al.picUrl,
      });
      if (that.data.playtime) {
        wx.seekBackgroundAudio({
          position: that.data.playtime,
        })
      }
      var app = getApp()
      app.globalData.musicid = that.data.id;
      var isExisted = false;
      for (var index = 0; index < getApp().globalData.playing.length; index++) {
        var savedid = getApp().globalData.playing[index];
        if (savedid.id == id) {
          isExisted = true
          break
        }
      }
      if (!isExisted) {
        getApp().globalData.playing.push({ id: id });
        getApp().globalData.playno = getApp().globalData.playing.length
      }
      var histories = that.data.histories;
      if (histories) {
        for (var index = 0; index < histories.length; index++) {
          var savedid = histories[index];
          if (savedid.id == id) {
            histories.isExisted = true;
            histories.splice(index, 1)
            break;
          }
        }
      }
      if (!histories) {
        histories = [];
      }
      id = parseInt(id)
      histories.push({ id: id });
      wx.setStorage({
        key: 'played',
        data: histories,
        success: function (res) {
          console.log("保存成功")
        }
      })

      console.log("play")
      let bgMusic = wx.getBackgroundAudioManager();
      bgMusic.onTimeUpdate(() => {
        this.setData({
          time: bgMusic.currentTime,
          alltime: bgMusic.duration,
          time1: this.timeToString(bgMusic.currentTime.toFixed(0)),
          time2: this.timeToString(bgMusic.duration.toFixed(0))
        })

        var i = that.data.currentIndex222
        if (that.data.checkTimes[i] <= bgMusic.currentTime) {
          that.setData({
            currentIndex222: i + 1,
            hang: i
          })
        }
        if (bgMusic.currentTime == bgMusic.duration) {
          this.next()
        }
      })
    }
    getApp().globalData.isPlayMusic = (!that.data.isPlayMusic)
    that.setData({
      isPlayMusic: (!that.data.isPlayMusic)
    })
  },
  onlyrictap: function () {
    var that = this
    that.setData({
      islyric: (!this.data.islyric)
    })
  },

  timeToString: function (duration) {

    let str = '';
    let minute = parseInt(duration / 60) < 10 ? ('0' + parseInt(duration / 60)) : (parseInt(duration / 60));

    let second = (duration % 60) < 10 ? ('0' + duration % 60) : (duration % 60);

    str = minute + ':' + second;

    return str;

  },



  last: function () {
    getApp().globalData.playno = getApp().globalData.playno - 1
    if (getApp().globalData.playno <= -1) {
      getApp().globalData.playno = getApp().globalData.playing.length - 1
    }
    if (getApp().globalData.playing.length == 1) {
      getApp().globalData.playno = 0
    }
    this.onLoad({ id: id, playnow: true })
  },

  next: function () {
    getApp().globalData.playno = getApp().globalData.playno + 1
    if (getApp().globalData.playno >= getApp().globalData.playing.length) {
      getApp().globalData.playno = 0
    }
    if (getApp().globalData.playing.length == 1) {
      getApp().globalData.playno = 0
    }
    var id = getApp().globalData.playing[getApp().globalData.playno].id
    this.onLoad({ id: id, playnow: true })
  },



  ontest: function (text) {
    var that = this;
    var result = [];
    var lines = text.split('\n');
    var pattern = /\[\d{2}:\d{2}.\d{2}\]/g;
    var pattern2 = /\[\d{2}:\d{2}.\d{3}\]/g
    var times = [];
    var values = []
    lines[lines.length - 1].length === 0 && lines.pop();
    for (var i = 0; i < lines.length; i++) {
      var time = lines[i].match(pattern);
      var value = lines[i].replace(pattern, '');
      if (!time) {
        time = lines[i].match(pattern2);
        value = lines[i].replace(pattern2, '');
      }
      if (time) {
        time = time[0].slice(1, -1)
        time = time.split(":")
        time = parseInt(time[0] * 60) + parseInt(time[1])
        times.push(time)
        values.push(value)
      }
      that.setData({
        checkTimes: times,
        storyContent: values
      })
    }
  },


  playnow: function (id) {

    var that = this

    var p1 = new Promise(function (resolve, reject) {
      wx.getStorage({
        key: 'played',
        success: function (res) {
          that.setData({
            histories: res.data
          })
        },
      })
      resolve()
    });
    var p2 = new Promise(function (resolve, reject) {
      network.getDetail({
        id: id,
        success: function (song) {
          that.setData({
            song: song
          })
        }
      })
      resolve()
    });
    var p3 = new Promise((resolve, reject) => {
      network.getLyric({
        id: id,
        success: function (lrc) {
          that.setData({
            lyric: lrc
          })
          that.ontest(lrc)
        },
      })
      resolve()
    });

    var p4 = new Promise((resolve, reject) => {
      network.getPlay({
        id: id,
        success: function (url) {
          that.setData({
            url: url,
            isPlayMusic
          })
        },
      })
      resolve()
    });

    Promise.all([p1, p2, p3, p4]).then(function () {
      console.log("SSS")
    });
  },


  

})